﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BrnMall.Manager.Domain.Distribution;
using PetaPoco;

namespace BrnMall.Manager.Manager.Distribution
{
    public static class BrokerageManager
    {
        #region 佣金提现设置

        public static BrokerageConfig GetBrokerageConfig(int storeId)
        {
            using (var db = new QDMallDatabase())
            {
                var result = db.SingleOrDefault<BrokerageConfig>("select top 1 * from dis_BrokerageConfig where storeid=@0",storeId);
                if (result != null) return result;
                result=new BrokerageConfig() {StoreId = storeId,RequestMaxAmount = 0,RequestMinAmount = 0};
                db.Insert(result);
                return result;
            }
        }

        #endregion

        #region 佣金明细
        /// <summary>
        /// 添加佣金明细
        /// </summary>
        /// <param name="brokerage"></param>
        public static void AddBrokerage(Brokerage brokerage)
        {
            using (var db = new QDMallDatabase())
            {
                db.Insert(brokerage);
            }
        }
        /// <summary>
        /// 判断订单是否已经结算过
        /// </summary>
        /// <param name="osn"></param>
        /// <returns></returns>
        public static bool CheckBrokerage(string osn)
        {
            if (string.IsNullOrEmpty(osn)) return false;
            using (var db = new QDMallDatabase())
            {
                var id = db.ExecuteScalar<object>("select top 1 id from dis_Brokerage where orderno=@0", osn);
                return id != null;
            }
        }

        /// <summary>
        /// 添加佣金明细
        /// </summary>
        /// <param name="brokerage"></param>
        public static void AddBrokerageAndCaculate(Brokerage brokerage)
        {
            if (brokerage.StoreId == 68) return;//玖玖客不需要自动升级
            using (var db = new QDMallDatabase())
            {
                db.BeginTransaction();
                db.Insert(brokerage);
                var dis = DistributorManager.GetDistributorByUserId(brokerage.UserId);
                dis.OrdersCount += 1;
                dis.OrdersTotal += brokerage.OrderAmount;
                dis.AccountBalance += brokerage.BrokerageAmount;
                var nextGradeId = db.ExecuteScalar<object>(dis.IsAgent == 0 ? "select top 1 id from dis_Grade where storeid=@1 and BrokerageLimit<=@0 and GradeType=0 order by BrokerageLimit desc" : "select top 1 id from dis_Grade where storeid=@1 and BrokerageLimit<=@0 and GradeType=1 order by BrokerageLimit desc", dis.OrdersTotal,dis.StoreId);
                if (nextGradeId!=null)
                    dis.GradeId =int.Parse(nextGradeId.ToString());
                DistributorManager.UpdateDistributor(dis);
                db.CompleteTransaction();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Brokerage GetBrokerage(int id)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<Brokerage>(id);
            }
        }
        /// <summary>
        /// 删除佣金
        /// </summary>
        /// <param name="id">佣金ID</param>
        /// <returns></returns>
        public static bool DeleteBrokerage(int id)
        {
            var brokerage = GetBrokerage(id);
            if (brokerage == null || brokerage.Status == 21) return false;
            using (var db = new QDMallDatabase())
            {
                //更新分销商的分销记录和金额
                var dis = DistributorManager.GetDistributorByUserId(brokerage.UserId);
                if(dis.AccountBalance<brokerage.BrokerageAmount)return false;
                dis.AccountBalance = dis.AccountBalance - brokerage.BrokerageAmount;
                dis.OrdersTotal = dis.OrdersTotal - brokerage.OrderAmount;
                DistributorManager.UpdateDistributor(dis);

                db.Delete<Brokerage>(id);//删除数据库记录
                return true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="brokerage"></param>
        public static void UpdateBrokerage(Brokerage brokerage)
        {
            using (var db = new QDMallDatabase())
            {
                db.Update(brokerage);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="disStoreName"></param>
        /// <param name="tradeTimeStart"></param>
        /// <param name="tradeTimeEnd"></param>
        /// <param name="orderNo"></param>
        /// <param name="page"></param>
        /// <param name="itemsPerPage"></param>
        /// <returns></returns>
        public static Page<Brokerage> GetBrokerageStoreListPage(int storeId, string disStoreName, DateTime tradeTimeStart, DateTime tradeTimeEnd, string orderNo, long page, long itemsPerPage)
        {
            using (var db = new QDMallDatabase())
            {
                var sql = new StringBuilder();
                sql.Append("select a.* from dis_Brokerage a left join dis_Distributor b on a.userid=b.userid where 1=1");
                if (storeId > 0)
                    sql.AppendFormat(" and a.storeid={0}", storeId);
                if (!string.IsNullOrEmpty(disStoreName))
                    sql.AppendFormat(" and b.DisStoreName like '{0}%'", disStoreName);
                if (tradeTimeStart.Year != 1900)
                    sql.AppendFormat(" and datediff(day,a.TradeTime,'{0:yyyy-MM-dd}')<=0 ", tradeTimeStart);
                if(tradeTimeEnd.Year!=1900)
                    sql.AppendFormat(" and datediff(day,a.TradeTime,'{0:yyyy-MM-dd}')>=0 ", tradeTimeEnd);
                if (!string.IsNullOrEmpty(orderNo))
                    sql.AppendFormat(" and a.orderno='{0}'", orderNo);
                sql.Append(" order by TradeTime desc");
                Trace.TraceInformation(sql.ToString());
                return db.Page<Brokerage>(page, itemsPerPage,sql.ToString());
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="page"></param>
        /// <param name="itemsPerPage"></param>
        /// <returns></returns>
        public static Page<Brokerage> GetBrokerageUserListPage(int userId, long page, long itemsPerPage)
        {
            using (var db = new QDMallDatabase())
            {
                return db.Page<Brokerage>(page, itemsPerPage,
                    "select * from dis_Brokerage where userid=@0 order by TradeTime desc", userId);
            }
        }
        

        #endregion

        #region 佣金提现
        /// <summary>
        /// 添加提现记录
        /// </summary>
        /// <param name="request"></param>
        public static int AddBrokerageRequest(BrokerageRequest request)
        {
            using (var db = new QDMallDatabase())
            {
                var index=db.Insert(request);
                var r = 0;
                int.TryParse(index.ToString(), out r);
                return r;

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static BrokerageRequest GetBrokerageRequest(int id)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<BrokerageRequest>(id);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="brsn"></param>
        /// <returns></returns>
        public static BrokerageRequest GetBrokerageRequestByBrsn(string brsn)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<BrokerageRequest>("select * from dis_BrokerageRequest where brsn=@0",brsn);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        public static void UpdateBrokerageRequest(BrokerageRequest request)
        {
            using (var db = new QDMallDatabase())
            {
                db.Update(request);
            }
        }

        public static void DeleteBrokerageRequest(int id)
        {
            using (var db = new QDMallDatabase())
            {
                db.Delete<BrokerageRequest>(id);
            }
        }
        /// <summary>
        /// 获取提现记录
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="disStoreName"></param>
        /// <param name="requestTimeStart"></param>
        /// <param name="requestTimeEnd"></param>
        /// <param name="sendTimeStart"></param>
        /// <param name="sendTimeEnd"></param>
        /// <param name="payStatus"></param>
        /// <param name="status"></param>
        /// <param name="page"></param>
        /// <param name="itemsPerPage"></param>
        /// <returns></returns>
        public static Page<BrokerageRequest> GetBrokerageRequestStoreListPage(int storeId, string disStoreName, DateTime requestTimeStart, DateTime requestTimeEnd,DateTime sendTimeStart,DateTime sendTimeEnd,int payStatus=-1,int status=-1, long page=1, long itemsPerPage=15)
        {
            using (var db = new QDMallDatabase())
            {
                var sql = new StringBuilder();
                sql.AppendFormat("select a.* from dis_BrokerageRequest a left join dis_Distributor b on a.userid=b.userid where a.storeid={0}", storeId);
                if (!string.IsNullOrEmpty(disStoreName))
                    sql.AppendFormat(" and b.DisStoreName like '{0}%'", disStoreName);
                if (requestTimeStart.Year != 1900)
                    sql.AppendFormat(" and datediff(day,a.RequestTime,'{0:yyyy-MM-dd}')<=0 ", requestTimeStart);
                if (requestTimeEnd.Year != 1900)
                    sql.AppendFormat(" and datediff(day,a.RequestTime,'{0:yyyy-MM-dd}')>=0 ", requestTimeEnd);
                if (sendTimeStart.Year != 1900)
                    sql.AppendFormat(" and datediff(day,a.SendTime,'{0:yyyy-MM-dd}')<=0 ", sendTimeStart);
                if (sendTimeEnd.Year != 1900)
                    sql.AppendFormat(" and datediff(day,a.SendTime,'{0:yyyy-MM-dd}')>=0 ", sendTimeEnd);
                if (payStatus > -1)
                    sql.AppendFormat(" and a.paystatus={0}", payStatus);
                if (status > -1)
                    sql.AppendFormat(" and a.status={0}", status);
                sql.Append(" order by RequestTime desc");
                return db.Page<BrokerageRequest>(page, itemsPerPage,sql.ToString());
            }
        }

        /// <summary>
        /// 获取用户提现记录
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="status">审核状态0待审核，1已审核，2已拒绝</param>
        /// <param name="payStatus">支付状态0:待发放1，已发放</param>
        /// <param name="page"></param>
        /// <param name="itemsPerPage"></param>
        /// <returns></returns>
        public static Page<BrokerageRequest> GetBrokerageRequestUserListPage(int userId,int status,int payStatus, long page, long itemsPerPage)
        {
            using (var db = new QDMallDatabase())
            {
                var sql =new StringBuilder();
                sql.AppendFormat("select * from dis_BrokerageRequest where userid={0}", userId);
                if (status > -1)
                    sql.AppendFormat(" and status={0}", status);
                if (payStatus > -1)
                    sql.AppendFormat(" and paystatus={0}", payStatus);
                sql.AppendFormat(" order by RequestTime desc");
                return db.Page<BrokerageRequest>(page, itemsPerPage,sql.ToString());
            }
        }

        #endregion

        #region 佣金发放
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static BrokerageSendRecord GetBrokerageSendRecord(int id)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<BrokerageSendRecord>(id);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        public static int AddBrokerageSendRecord(BrokerageSendRecord record)
        {
            using (var db = new QDMallDatabase())
            {
                db.Insert(record);
                return record.Id;
            }
        }

        public static void UpdateBrokerageSendRecord(BrokerageSendRecord record)
        {
            using (var db = new QDMallDatabase())
            {
                db.Update(record);
            }
        }

        public static void DeleteBrokerageSendRecord(int id)
        {
            using (var db = new QDMallDatabase())
            {
                db.Delete<BrokerageSendRecord>(id);
            }
        }

        public static IList<BrokerageSendRecord> GetBrokerageSendRecords(int brid)
        {
            using (var db = new QDMallDatabase())
            {
                return db.Fetch<BrokerageSendRecord>(
                    "select * from dis_BrokerageSendRecord where brid=@0 order by SendTime desc ", brid);
            }
        }


        #endregion
    }
}
